<script setup>
import { articleAddListService, articleUpdateListService } from '@/api/article'
import { ElMessage } from 'element-plus'
import {ref,inject} from 'vue'
const getChannels = inject('getChannels')
// 控制弹出框是否可见
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const formRef = ref()

const formModel = ref({
  cate_name:'',
  cate_alias:''
})
const rules = {
  cate_name:[
    {required:true,message:'请输入分类名称',trigger:'blur'},
    {pattern:/^\S{1,10}$/,message:'请输入1-10位的非空字符',trigger:'blur'}
  ],
  cate_alias:[
    {required:true,message:'请输入分类别名',trigger:'blur'},
    {pattern:/^[a-zA-Z0-9]{1,15}$/,message:'请输入1-10位的字母或数字',trigger:'blur'}

  ]
}
const handlConfirm = async ()=>{
  if(formModel.value.id){
    // 存在id即为修改文章分类
    // 验证表单输入的数据合法性
    await formRef.value.validate()
    const res = await articleUpdateListService(formModel.value)

    if(res.data.code === 0){
      dialogFormVisible.value = false
      ElMessage.success(res.data.message)
      getChannels()
    }else{
      dialogFormVisible.value = false
      ElMessage.error(res.data.message)
    }
  }else{
    await formRef.value.validate()
    const res = await articleAddListService(formModel.value)
    if(res.data.code === 0){
      dialogFormVisible.value = false
      ElMessage.success(res.data.message)
      getChannels()
    }else{
      dialogFormVisible.value = false
      ElMessage.error(res.data.message)
    }
  }

}
// 组件对外暴露的方法open(),当有数据传入则在表单中回显传入的数据,没有则显示空表单。
const open = async (value)=>{
  dialogFormVisible.value = true
  formModel.value = {...value}

}
defineExpose({
  open
})
</script>
<template>
  <!-- 编辑弹出框 -->
  <el-dialog v-model="dialogFormVisible" :title="formModel.id ? '编辑文章分类':'添加文章分类'" width="500">
    <el-form :model="formModel" :rules="rules">
      <el-form-item prop="cate_name" label="分类名称" :label-width="formLabelWidth" ref="formRef">
        <el-input v-model="formModel.cate_name" autocomplete="off" />
      </el-form-item>
      <el-form-item prop="cate_alias" label="分类别名" :label-width="formLabelWidth">
        <el-input v-model="formModel.cate_alias" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handlConfirm">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
